<?php
class UsersController extends AppController {

    var $name = 'Users';
    var $helpers = array('Html', 'Form');
    var $components = array('Session','Email');

    
    function beforeFilter()
    {        
        parent::beforeFilter();
        $a_ActionAccess = array( 'register', 'save', 'login' );
    	$user = $this->Session->read('User.User');
     	if ( !in_array($this->params['action'], $a_ActionAccess) )
     	{
     		if ( !$user )
     		{
     			$this->redirect(array('controller'=>'pages','action' => 'display'));
     		}
     	}
     	else 
     	{
     		if( $user )
     		{
     			$this->redirect(array('controller'=>'pages','action' => 'display'));
     		}
     	}
    }
    
    function index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function add() {
        if (!empty($this->data)) {
            $this->User->create();
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for User', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->del($id)) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('The User could not be deleted. Please, try again.', true));
        $this->redirect(array('action' => 'index'));
    }


    function admin_index() {
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());
    }

    function admin_view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('user', $this->User->read(null, $id));
    }

    function admin_add() {
        if (!empty($this->data)) {
            $this->User->create();
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
    }

    function admin_edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid User', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                $this->Session->setFlash(__('The User has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->User->read(null, $id);
        }
    }

    function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for User', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->User->del($id)) {
            $this->Session->setFlash(__('User deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('The User could not be deleted. Please, try again.', true));
        $this->redirect(array('action' => 'index'));
    }
    
    //TODO register user
    function register()
    {
        $this->layout =  null;
    
    }
    
    //TODO login page
    function login() 
    {
        Configure::write('debug', 0);
        $this->layout =  null;
        $this->layout =  false;
        if(!empty($this->data)) 
        {
        	if( $this->data['UserPhar'] )
        	{
        		$this->data['User'] = $this->data['UserPhar'];
        		unset($this->data['UserPhar']);
        	}
            $username = $this->data['User']['Username'];
            $password = md5($this->data['User']['Password']);
            $usertype = $this->data['User']['UserType'];
            if ( $usertype == '1' )        
            	$user = $this->User->find('first',array('conditions'=>array('User.Username'=>$username,'User.Password'=>$password, 'User.UserType' => $usertype ),'recursive'=>0));
            else 
            	$user = $this->User->find('first',array('conditions'=>array('User.Username'=>$username,'User.Password'=>$password, 'User.UserType <>' => '1'),'recursive'=>0));
            	
            if(!empty($user))
            {
                // Create login key
                $loginTime = date("Y-m-d H:i:s");
                $loginKey = $user['User']['id'] . "key" . $loginTime;
                $loginKey = md5($loginKey);                
                // ----------------
                
                // update login time
                $this->User->id = $user['User']['id'];
                $this->User->saveField('LastLoggedIn',$loginTime);
                $this->User->saveField('login_key',$loginKey);
                $this->User->saveField('login_count',$user['User']['login_count'] + 1);
                
                $this->Session->write('User',$user );
                
                $a_Errors["success"]="true";
                $a_Errors["User"]=$user['User'];
                $a_Errors['message'] = 'Success';
                echo json_encode($a_Errors);
                $this->render(false);
            }
            else
            {
                $a_Errors["success"]="faild";
                $a_Errors['message'] = 'Username or Password is incorrect!';
                echo json_encode($a_Errors);
                $this->render(false);
            }
        }
    }
    //TODO logout page
    function logout() 
    {
		$this->Session->delete('User');        
		$this->redirect(array('controller'=>'pages','action'=>'display'));
    }

}
?>